package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.entity.VehicleUseRecord;
import com.vehiclemanagement.service.VehicleUseRecordService;
import com.vehiclemanagement.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 车辆出车记录控制器
 */
@RestController
@RequestMapping("/vehicle-use")
public class VehicleUseRecordController {
    
    @Autowired
    private VehicleUseRecordService vehicleUseRecordService;
    
    /**
     * 分页查询出车记录列表
     */
    @GetMapping("/list")
    public R<IPage<VehicleUseRecord>> list(
            @RequestParam(value = "current", defaultValue = "1") Integer current,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "searchTerm", required = false) String searchTerm,
            @RequestParam(value = "vehicleId", required = false) Long vehicleId,
            @RequestParam(value = "driverId", required = false) Long driverId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "startDate", required = false) 
                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startDate,
            @RequestParam(value = "endDate", required = false) 
                @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endDate) {
        IPage<VehicleUseRecord> page = vehicleUseRecordService.pageRecords(
                current, size, searchTerm, vehicleId, driverId, status, startDate, endDate);
        return R.ok(page);
    }
    
    /**
     * 获取出车记录详情
     */
    @GetMapping("/{id}")
    public R<VehicleUseRecord> getById(@PathVariable Long id) {
        VehicleUseRecord record = vehicleUseRecordService.getRecordById(id);
        if (record == null) {
            return R.error("出车记录不存在");
        }
        return R.ok(record);
    }
    
    /**
     * 添加出车记录
     */
    @PostMapping
    public R<Boolean> add(@RequestBody VehicleUseRecord record) {
        System.out.println("接收到添加出车记录请求，数据：" + record);
        
        // 检查必要字段
        if (record.getVehicleId() == null) {
            return R.error("车辆ID不能为空");
        }
        if (record.getDriverId() == null) {
            return R.error("驾驶员ID不能为空");
        }
        if (record.getPurpose() == null || record.getPurpose().trim().isEmpty()) {
            return R.error("出车用途不能为空");
        }
        
        // 检查车辆是否已被使用
        if (vehicleUseRecordService.hasActiveUseByVehicleId(record.getVehicleId())) {
            return R.error("车辆已被使用，请选择其他车辆");
        }
        
        // 检查驾驶员是否已被指派
        if (vehicleUseRecordService.hasActiveUseByDriverId(record.getDriverId())) {
            return R.error("驾驶员已被指派其他车辆，请选择其他驾驶员");
        }
        
        boolean result = vehicleUseRecordService.addRecord(record);
        if (result) {
            return R.ok(true);
        } else {
            System.out.println("添加出车记录失败，服务层返回false");
            return R.error("添加失败");
        }
    }
    
    /**
     * 更新出车记录
     */
    @PutMapping
    public R<Boolean> update(@RequestBody VehicleUseRecord record) {
        if (record.getId() == null) {
            return R.error("出车记录ID不能为空");
        }
        boolean result = vehicleUseRecordService.updateRecord(record);
        return result ? R.ok(true) : R.error("更新失败");
    }
    
    /**
     * 删除出车记录
     */
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        System.out.println("接收到删除出车记录请求，ID: " + id);
        
        boolean result = vehicleUseRecordService.deleteRecord(id);
        
        if (result) {
            System.out.println("成功删除出车记录，ID: " + id);
            return R.ok(true);
        } else {
            System.out.println("删除出车记录失败，ID: " + id);
            return R.error("删除失败");
        }
    }
    
    /**
     * 审批出车申请
     */
    @PutMapping("/approve/{id}")
    public R<Boolean> approve(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        System.out.println("接收到审批出车申请请求，ID: " + id);
        
        String approver = (String) params.get("approver");
        Boolean approved = (Boolean) params.get("approved");
        String remark = (String) params.get("remark");
        
        if (approver == null || approver.trim().isEmpty()) {
            return R.error("审批人不能为空");
        }
        if (approved == null) {
            return R.error("审批结果不能为空");
        }
        
        boolean result = vehicleUseRecordService.approveRecord(id, approver, approved, remark);
        
        return result ? R.ok(true) : R.error("审批失败");
    }
    
    /**
     * 确认出车
     */
    @PutMapping("/start/{id}")
    public R<Boolean> startUse(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        System.out.println("接收到确认出车请求，ID: " + id);
        
        Double startMileage = ((Number) params.get("startMileage")).doubleValue();
        
        if (startMileage == null) {
            return R.error("出车里程数不能为空");
        }
        
        boolean result = vehicleUseRecordService.startUse(id, startMileage);
        
        return result ? R.ok(true) : R.error("确认出车失败");
    }
    
    /**
     * 确认归还
     */
    @PutMapping("/return/{id}")
    public R<Boolean> returnVehicle(@PathVariable Long id, @RequestBody Map<String, Object> params) {
        System.out.println("接收到确认归还请求，ID: " + id);
        
        Double endMileage = ((Number) params.get("endMileage")).doubleValue();
        
        if (endMileage == null) {
            return R.error("归还里程数不能为空");
        }
        
        boolean result = vehicleUseRecordService.returnVehicle(id, endMileage);
        
        return result ? R.ok(true) : R.error("确认归还失败");
    }
    
    /**
     * 检查车辆是否可用
     */
    @GetMapping("/check-vehicle/{vehicleId}")
    public R<Boolean> checkVehicleAvailability(@PathVariable Long vehicleId) {
        boolean hasActiveUse = vehicleUseRecordService.hasActiveUseByVehicleId(vehicleId);
        return R.ok(!hasActiveUse);
    }
    
    /**
     * 检查驾驶员是否可用
     */
    @GetMapping("/check-driver/{driverId}")
    public R<Boolean> checkDriverAvailability(@PathVariable Long driverId) {
        boolean hasActiveUse = vehicleUseRecordService.hasActiveUseByDriverId(driverId);
        return R.ok(!hasActiveUse);
    }
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public R<String> test() {
        return R.ok("车辆出车记录API正常运行！");
    }
} 